var express = require('express');
var fs = require('fs');
var router = express.Router();
var multer = require('multer');
var userModel = require('../../models/user/user');
var upload = multer({ dest: 'public/images/profile-pic/' })

router.post('/', upload.single('img'), function (req, res, next) {
    let file = req.file
    let params = req.body
    fs.renameSync(file.path, "public/images/profile-pic/" + file.originalname)
    let profilePic = file.originalname  // 新图片名称
    // 根据旧文件名称删除头像文件夹的同名文件
    userModel.find({ openid: params.openid }, (err, docs) => {
        let oldPic = docs[0].profilePic
        fs.unlink(`public/images/profile-pic/${oldPic}`, (err) => { console.log(err) })
    })
    // 将新文件名称更新到数据表中
    userModel.updateOne({ openid: params.openid }, { $set: { profilePic: profilePic } }, {}, () => {
        res.json({ code: 200, msg: 'uploaded!' })
    })
})

module.exports = router;
